package cn.jx.asc.login.controller;

import cn.jx.asc.common.untils.SecurityUtils;
import cn.jx.asc.common.untils.StringToTimeUtils;
import cn.jx.asc.socket.InstructAndResult;
import cn.jx.asc.user.pojo.*;
import cn.jx.asc.user.service.UserService;
import cn.jx.asc.user.vo.DataShow;
import com.alibaba.fastjson.JSON;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller("loginController_Android")
@RequestMapping("/Login")
public class LoginController_Android {

    @Autowired
    private UserService userService;

    SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss");


    /**
     * @author LaiWeiXing
     * @date 2018/6/20 11:18
     * @describe 安卓端注册用户
     */
    @RequestMapping("/sign_android")
    @ResponseBody
    public String sign(User user){
        //获取用户注册信息的用户名
        String username = user.getUserName();
        //查询数据库查看用户名是否已经存在
        User user_db = userService.findUserByname(username);
        if(user_db==null){
            try {
                user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            int row = userService.addUser(user);
            if(row>0){
                return "success";
            }
        }
        return "fail";
    }

    /**
     * @author ZhouGuoWei
     * @date 2018/6/1 15:52
     * @describe 安卓端检查登入
     */
    @RequestMapping("/check_android")
    @ResponseBody
    public String checkLogin(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        String flag =request.getParameter("checkbox");

        //先检查是否有这个用户
        User user = userService.findUserByname(username);
        String userStr = JSON.toJSONString(user);
        if(user!=null){
            //检查密码是否相等
            if(SecurityUtils.checkPassword(pwd,user.getPassword())){
                //如果勾选了记住密码
                if("1".equals(flag)){
                    Cookie cookie_name = new Cookie("username",username);
                    Cookie cookie_pwd = new Cookie("pwd",pwd);
                    cookie_name.setMaxAge(60*60*24*3);                       //设置cookie的有效期为三天
                    cookie_pwd.setMaxAge(60*60*24*3);
                    cookie_name.setPath("/Login/login");                      //设置cookie的携带路径
                    cookie_pwd.setPath("/Login/login");
                    response.addCookie(cookie_name);                          //向客户端发送cookie
                    response.addCookie(cookie_pwd);
                    request.getSession().setAttribute("USER_SESSION",user);    //将用于存入SESSION中
                    //将正确的信息返回给前端
                    return userStr;
                }else {
                    request.getSession().setAttribute("USER_SESSION",user);
                    //将正确的信息返回给前端
                    return userStr;
                }

            }else {
                return "fail";
            }
        }else {
            return "fail";
        }

    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/22 11:30
     * @describe 安卓端修改个人信息
     */
    @RequestMapping("/update_android")  //更新修改用户信息
    @ResponseBody
    public String update(HttpSession session, HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        String userIdStr = request.getParameter("userId");
        String userName = request.getParameter("userName");
        String realName = request.getParameter("realName");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String mail = request.getParameter("mail");
        String tel = request.getParameter("tel");
        String address = request.getParameter("address");

        //封装一个user对象
        User user = new User();
        Integer userId = Integer.valueOf(userIdStr);
        user.setUserId(userId);
        user.setPassword(SecurityUtils.encryptPassword(password));
        user.setUserName(userName);
        user.setRealName(realName);
        user.setMail(mail);
        user.setTel(tel);
        user.setAddress(address);
        int row = userService.updateUser(user);

        if (userName == "" || realName == "" || password == "" || repassword == "") {
            return "fail";
        } else if (!password.equals(repassword)) {
            return "fail";
        } else if (row > 0) {
            return "OK";
        } else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/24 17:44
     * @describe 安卓端查找用户
     */
    @RequestMapping("/findUser_android")
    @ResponseBody
    public String selectUserByUserId(HttpServletRequest request){
        //接收传递过来的用户id
        String userIdStr = request.getParameter("userId");
        Integer userId = Integer.valueOf(userIdStr);
        //查找用户
        User user = userService.selectUserByPrimaryKey(userId);
        if(user!=null){
            String userJsonStr = JSON.toJSONString(user);
            return userJsonStr;
        }else{
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/25 16:28
     * @describe 安卓端显示区域列表
     */
    @RequestMapping(value="/areaClassification_android" ,produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String areaClassification(HttpServletRequest request){
        //获取到当前用户的userId
        String userIdStr = request.getParameter("userId");
        Integer userId = Integer.valueOf(userIdStr);
        //根据userId查询当前用户管理的区域
        List<Region> regionList = null;
        if(userId!=null){
            regionList = userService.selectAllByUserId(userId);
            if(regionList!=null){
                String regionListJsonStr = JSON.toJSONString(regionList);
                return regionListJsonStr;
            }
        }
        return "fail";
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/21 15:55
     * @describe 安卓端添加区域
     */
    @RequestMapping("/addArea_android")
    @ResponseBody
    public String addArea(HttpServletRequest request){
        //获取到区域名和用户id
        String areaName = request.getParameter("regionName");
        String userIdStr = request.getParameter("userId");
        Integer userId = Integer.valueOf(userIdStr);
        //封装一个Region区域对象
        Region region = new Region();
        region.setRegionName(areaName);
        region.setUserId(userId);
        int row = userService.addRegion(region);
        if(row>0){
            return "suc";
        }else{
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/21 20:44
     * @describe 安卓端修改区域名
     */
    @RequestMapping("/updateArea_android")
    @ResponseBody
    public String updateArea(HttpServletRequest request){
        //获取到区域id和修改后的区域名
        String regionIdStr = request.getParameter("regionId");
        Integer regionId = Integer.valueOf(regionIdStr);
        String regionName = request.getParameter("regionName");
        //封装一个Region区域对象
        Region region = new Region();
        region.setRegionId(regionId);
        region.setRegionName(regionName);
        int row = userService.updateAreaName(region);
        if(row>0){
            return "suc";
        }else{
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/21 15:55
     * @describe 安卓端删除区域
     */
    @RequestMapping("/deleteArea_android")
    @ResponseBody
    public String deleteArea(HttpServletRequest request){
        //获取当前区域id
        String regionIdStr = request.getParameter("regionId");
        Integer regionId = Integer.valueOf(regionIdStr);
        if(regionId!=null){
            int row = userService.deleteRegionByRegionId(regionId);
            if(row>0){
                return "success";
            }else{
                return "fail";
            }
        }
        return "fail";
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/26 9:54
     * @describe 安卓端显示组列表
     */
    @RequestMapping(value = "/groupClassification_android" ,produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String groupClassification(HttpServletRequest request){
        //获取到当前用户的userId
        String userIdStr = request.getParameter("userId");
        Integer userId = Integer.valueOf(userIdStr);
        List<Group> groupList = null;
        if(userId!=null){
            groupList =  userService.selectAllGroupByUserId(userId);
            if(groupList!=null){
                String groupListJsonStr = JSON.toJSONString(groupList);
                return groupListJsonStr;
            }
        }
        return "fail";
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/26 17:25
     * @describe 根据区域id返回组集合
     */
    @RequestMapping(value = "/findGroupListByRegionId_android" ,produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String findGroupListByRegionId(HttpServletRequest request){
        //接收到区域id
        String regionIdStr = request.getParameter("regionId");
        Integer regionId = Integer.valueOf(regionIdStr);
        List<Group> groupList = userService.findGroupListByRegionId(regionId);
        if(groupList!=null){
            String groupListJsonStr = JSON.toJSONString(groupList);
            return groupListJsonStr;
        }else{
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/22 14:33
     * @describe 安卓端获取到管理员id下的种植种类集合，并转换成json格式返回
     */
    @RequestMapping(value = "/cropTypeListToJson_android" ,produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String croupTypeListToJson(HttpServletRequest request){
        //查找管理员id下的专家方案集合
        List<Plan> planList = userService.findPlanListByUserId(100000003);
        if(!planList.isEmpty()){
            //将集合转换成json格式
            String planListJsonStr = JSON.toJSONString(planList);
            return planListJsonStr;
        }else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/22 16:13
     * @describe 安卓端添加组
     */
    @RequestMapping("/addGroup_android")
    @ResponseBody
    public String addGroup(HttpServletRequest request){
        //获取到表单数据
        String groupName = request.getParameter("groupName");
        String croupType = request.getParameter("cropType");
        String plantTime = request.getParameter("plantTime");
        String regionName = request.getParameter("regionName");
        String regionIdStr = request.getParameter("regionId");
        String sensorName = request.getParameter("sensorName");
        //根据区域id查找到该区域对象
        Integer regionId = Integer.valueOf(regionIdStr);
        //封装一个Group对象
        Group group = new Group();
        group.setGroupName(groupName);
        group.setCroupType(croupType);
        try {
            group.setPlantTime(dataFormat.parse(plantTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        group.setRegionId(regionId);
        //添加组
        int row = userService.insertGroup(group);
        Integer groupId = userService.findLastGroupId();
        if(row>0){
            //封装一个Sensor对象
            Sensor sensor = new Sensor();
            sensor.setSensorName(sensorName);
            sensor.setTimeInterval((short) 30);
            sensor.setGroupId(groupId);
            //添加传感器
            int row2 = userService.insertSensor(sensor);
            if(row2>0){
                return "success";
            }else{
                return "fail";
            }
        }else{
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/25 9:21
     * @describe 安卓端删除组
     */
    @RequestMapping("/deleteGroup_android")
    @ResponseBody
    public String deleteGroup(HttpServletRequest request){
        //获取到传输过来的id值
        String groupIdStr = request.getParameter("groupId");
        Integer groupId = Integer.valueOf(groupIdStr);
        //删除组
        int row = userService.deleteGroup(groupId);
        if(row>0){
            return "success";
        }else{
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/24 21:29
     * @describe 安卓端修改组
     */
    @RequestMapping("/updateGroup_android")
    @ResponseBody
    public String updateGroup(HttpServletRequest request){
        //获取到表单数据
        String groupName = request.getParameter("groupName");
        String croupType = request.getParameter("cropType");
        String plantTime = request.getParameter("plantTime");
        String groupIdStr = request.getParameter("groupId");
        Integer groupId = Integer.valueOf(groupIdStr);
        String regionIdStr = request.getParameter("regionId");
        Integer regionId = Integer.valueOf(regionIdStr);
        //封装Group对象
        Group group = new Group();
        group.setGroupId(groupId);
        group.setGroupName(groupName);
        group.setCroupType(croupType);
        try {
            group.setPlantTime(dataFormat.parse(plantTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        group.setRegionId(regionId);
        int row = userService.updateGroup(group);
        if(row>0){
            return "success";
        }else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/28 10:49
     * @describe 安卓端插入定湿度,并把该组的阀门状态改为2
     */
    @RequestMapping("/insertHumidity_android")
    @ResponseBody
    public String insertHumidity(HttpServletRequest request) throws JSONException {
        //接收数据
        String groupIdStr = request.getParameter("groupId");
        Integer groupId = Integer.valueOf(groupIdStr);
        String humidityStr = request.getParameter("humidity");
        Short humidityInt = Short.valueOf(humidityStr);
        //发送给终端指令
        String humData = "{'flags':'4','hum':'"+humidityStr+"'}";       //湿度
        String conData = "{'flags':'5','valveNum':'5','data':'3'}";    //控制
        System.out.println("定湿度发送指令humData---"  +humData );
        System.out.println("定湿度发送指令conData---"  +conData );
        org.json.JSONObject jsonHumData = null;
        org.json.JSONObject jsonConData = null;
        try {
            jsonHumData = new org.json.JSONObject(humData);
            jsonConData = new org.json.JSONObject(conData);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //向终端发送请求数据
        int humId = InstructAndResult.sendInstructs(123456, jsonHumData);
        int conId = InstructAndResult.sendInstructs(123456, jsonConData);
        System.out.println("humId----------" + humId);
        System.out.println("conId----------" + conId);
        //封装一个Humiditi对象
        /*Humidity humidity = new Humidity();
        humidity.setHumidity(humidityInt);
        humidity.setGroupId(groupId);*/
        //插入定湿度表
        /*int row = userService.insertHumidity(humidity);
        if(row>0){
            userService.updateStateByGroupId(groupId);
            return "success";
        }
        return  "fail";*/
        //接收返回结果
        JSONObject resultHumJson = InstructAndResult.getResult(humId);
        JSONObject resultConJson = InstructAndResult.getResult(conId);
        System.out.println("定湿度返回结果---" + resultHumJson);
        System.out.println("定湿度控制返回结果---" + resultConJson);
        Integer humFlag = jsonHumData.getInt("flags");
        Integer conFlag = jsonHumData.getInt("flags");
        if (humFlag != -1 && humFlag != 0 && conFlag != -1 && conFlag != 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/28 11:56
     * @describe 根据组id查找该组阀门
    */
    @RequestMapping(value = "/findValveByGroupId_android" ,produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String findValveByGroupId(HttpServletRequest request){
        //接收数据
        String groupIdStr = request.getParameter("groupId");
        Integer groupId = Integer.valueOf(groupIdStr);
        //查找阀门
        List<Valve> valveList = userService.findValveByGroupId(groupId);
        String valveListJsonStr = JSON.toJSONString(valveList);
        System.out.println(valveListJsonStr);
        return valveListJsonStr;
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/28 20:53
     * @describe 根据用户id查找组集合
    */
    @RequestMapping(value = "/findGroupListByUserId_android" ,produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String findGroupListById(HttpServletRequest request){
        String userIdStr = request.getParameter("userId");
        Integer userId = Integer.valueOf(userIdStr);
        List<Group> groupList = userService.findGroupListByUserId(userId);
        String groupListJsonStr = JSON.toJSONString(groupList);
        return groupListJsonStr;
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/29 10:49
     * @describe 插入用户自定义控制
     */
    @RequestMapping("/insertControl_android")
    @ResponseBody
    public String insertControl(HttpServletRequest request) throws ParseException, JSONException {
        //接收参数
        /*String startTimeStr = request.getParameter("startTime");
        String stopTimeStr = request.getParameter("stopTime");
        String intervalDay = request.getParameter("intervalDay");
        String valveIdStr = request.getParameter("valveId");*/
        /*Integer valveId = Integer.valueOf(valveIdStr);
        *//*Date startTime = timeFormat.parse(startTimeStr);
        Date stopTime = timeFormat.parse(stopTimeStr);*//*
        //封装一个Control对象
        Control control = new Control();
        control.setStartTime(startTimeStr);
        control.setStopTime(stopTimeStr);
        control.setIntervalDay(intervalDay);
        control.setDaysRemaining((short) 30);
        control.setValveId(valveId);
        //插入数据库
        int row = userService.insertControl(control);
        System.out.println("row----"+row);
        if(row>0){
            return "success";
        }else{
            return "fail";
        }*/
        String timeInfos = request.getParameter("timeInfos");
        JSONArray jsonArray = new JSONArray(timeInfos);
        String times1 = "nullnullnull";
        String times2 = "nullnullnull";
        String times3 = "nullnullnull";
        String valveNum = jsonArray.getJSONObject(0).getString("valveId");
        for(int i=0;i<jsonArray.length();i++){
            JSONObject time=jsonArray.getJSONObject(i);
            if(i==0){
                times1=time.getString("startTime")+time.getString("stopTime")+time.getString("intervalDay");
            }
            times1 = StringToTimeUtils.timeToString(times1);
            if(i==1){
                times2=time.getString("startTime")+time.getString("stopTime")+time.getString("intervalDay");
            }
                times2 = StringToTimeUtils.timeToString(times2);
            if(i==2){
                times3=time.getString("startTime")+time.getString("stopTime")+time.getString("intervalDay");
            }
                times3 = StringToTimeUtils.timeToString(times3);
        }
        //将阀门id转换成valveNum
        if(valveNum.equals("400000066")){
            valveNum = "1";
        }else if(valveNum.equals("400000067")){
            valveNum = "2";
        }else if(valveNum.equals("400000068")){
            valveNum = "3";
        }else if(valveNum.equals("400000069")){
            valveNum = "4";
        }
        //发送给终端的指令
        String timeData = "{'flags':'3','valveNum':'"+valveNum+"','time1':'"+times1+"','time2':'"+times2+"','time3':'"+times3+"'}";
        System.out.println("发送定时数据-----" + timeData);
        //将数据转换为json对象
        org.json.JSONObject jsonTimeData = new org.json.JSONObject(timeData);
        //发送指令
        int timeId = InstructAndResult.sendInstructs(123456 ,jsonTimeData);
        System.out.println("发送指令id---"+timeId);
        //返回结果
        org.json.JSONObject resultTimeJson = InstructAndResult.getResult(timeId);
        Integer timeFlag = resultTimeJson.getInt("flags");
        System.out.println("返回定时结果resultTimeJson******************************" +resultTimeJson);
        if (timeFlag != -1 && timeFlag != 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/29 14:39
     * @describe 根据组id查找该组所有阀门,再插入用户自定义控制方案
    */
    @RequestMapping("/insertAllControl_android")
    @ResponseBody
    public String insertAllControl(HttpServletRequest request){
        //接收参数
        String groupIdStr = request.getParameter("groupId");
        Integer groupId = Integer.valueOf(groupIdStr);
        String startTimeStr = request.getParameter("startTime");
        String stopTimeStr = request.getParameter("stopTime");
        String intervalDay = request.getParameter("intervalDay");
        //根据组id查找该组所有阀门
        List<Valve> valveList = userService.findValveByGroupId(groupId);
        //插入用户自定义控制方案
        Integer valveId = null;
        Control control;
        int row = 0;
        for(Valve valve : valveList){
           valveId = valve.getValveId();
           //封装Control对象
            control = new Control();
            control.setStartTime(startTimeStr);
            control.setStopTime(stopTimeStr);
            control.setIntervalDay(intervalDay);
            control.setDaysRemaining((short) 30);
            control.setValveId(valveId);
            userService.insertControl(control);
            row++;
        }
        if(row>0){
            return "success";
        }else{
            return "fail";
        }

    }

    /**
     * @author ZhouGuoWei
     * @date 2018/7/5 10:32
     * @describe 安卓历史数据查询
     */
    @RequestMapping("/selectHistoryData_android")
    @ResponseBody
    public String selectHistoryData(HttpServletRequest request){
        String startTime = request.getParameter("startTime");
        String stopTime = request.getParameter("stopTime");
        DataShow dataShow = new DataShow();
        dataShow.setDataStart(startTime);
        dataShow.setDataEnd(stopTime);
        dataShow.setGroupId("300000069");
        List<Record> recordList = userService.findAndroidData(dataShow);  //根据用户查询时间来查询历史数据
        String recordListJson = JSON.toJSONString(recordList);
        return recordListJson;
    }


    /**
     * @author LaiWeiXing
     * @date 2018/7/2 8:33
     * @describe 安卓端删除阀门
    */
    @RequestMapping("/deleteValve_android")
    @ResponseBody
    public String deleteValve(HttpServletRequest request){
        //接收数据
        String valveIdStr = request.getParameter("valveId");
        Integer valveId = Integer.valueOf(valveIdStr);
        int row = userService.deleteValveByValveId(valveId);
        if(row>0){
            return "success";
        }else{
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/7/2 8:43
     * @describe 安卓端添加节点
    */
    @RequestMapping("/addValve_android")
    @ResponseBody
    public String addValve(HttpServletRequest request){
        //获取数据
        String nodeCode = request.getParameter("nodeCode");
        String groupIdStr = request.getParameter("groupId");
        Integer groupId = Integer.valueOf(groupIdStr);
        //封装一个Valve对象
        Valve valve = null;
        //定义一个变量记录插入数量
        int count = 0;
        //每插入一个节点，阀门表中插入四个阀门
        for(int i=1;i<=4;i++){
            valve = new Valve();
            valve.setValveName(String.valueOf(i));
            valve.setValveState((short) 0);
            valve.setControlType((short) 1);
            valve.setGroupId(groupId);
            valve.setNodeCode(nodeCode);
            userService.addValve(valve);
            count++;
        }
        if(count>0){
            return "success";
        }else{
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/7/4 16:58
     * @describe 安卓端刷新当前数据
    */
    @RequestMapping("/nowData_android")
    @ResponseBody
    public String getNowData(Model model) {
        //请求当前数据指令
        String dataFlag = "{\"flags\":\"1\"}";
        org.json.JSONObject jsonData = null;
        try {
            jsonData = new org.json.JSONObject(dataFlag);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println("jsonData---" + jsonData);
        //向终端发送请求数据
        int id = InstructAndResult.sendInstructs(123456, jsonData);
        //获取终端返回的数据
        org.json.JSONObject json = InstructAndResult.getResult(id);
        System.out.println("json----" + json);
        try {
            if (json.getInt("flags") != -1 && json.getInt("flags") != 0) {
                org.json.JSONObject dataJson = json.getJSONObject("data");
                Record record = new Record();
                record.setTemperature((short) dataJson.getInt("tem"));  //环境温度
                record.setTemperatureSoil((short) dataJson.getInt("soilTem"));  //土壤温度
                record.setHumidity((short) dataJson.getInt("hum")); //环境湿度
                record.setHumiditySoil((short) dataJson.getInt("soilTem")); //土壤湿度
                record.setCo2((short) dataJson.getInt("co2"));
                record.setSun(dataJson.getInt("sun"));
                System.out.println("record---" + record);
                return JSON.toJSONString(record);
            }else{
                return "fail";
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "fail";
    }

    /**
     * @author LaiWeiXing
     * @date 2018/7/4 21:39
     * @describe 安卓端改变单个阀门状态
    */
    @RequestMapping("changeAValve_android")
    @ResponseBody
    public String changeAValve(HttpServletRequest request) throws JSONException {
        //接收客户端发送的数据
        String valveName = request.getParameter("valveName");
        String valveState = request.getParameter("valveState");
        System.out.println("valveName----"+valveName);
        System.out.println("valveState----"+valveState);
        //发送给终端的数据
        String stateData = "{'flags':'2','data':{'valveNum':'"+valveName+"','state':'"+valveState+"'}}";  //阀门状态
        String conData = "{'flags':'5','valveNum':'"+valveName+"','data':'1'}";    //控制
        //将数据转换为json对象
        JSONObject jsonStateData = new JSONObject(stateData);
        JSONObject jsonConData = new JSONObject(conData);
        //发送指令
        int stateId = InstructAndResult.sendInstructs(123456 ,jsonStateData);
        int conId = InstructAndResult.sendInstructs(123456 ,jsonConData);
        //返回结果
        JSONObject resultStateJson = InstructAndResult.getResult(stateId);
        JSONObject resultConJson = InstructAndResult.getResult(conId);
        Integer stateFlag = resultStateJson.getInt("flags");
        Integer conFlag = resultConJson.getInt("flags");
        System.out.println("resultStateJson--------" + resultStateJson);
        System.out.println("resultConJson--------" + resultConJson);
        if (stateFlag != -1 && stateFlag != 0 && conFlag != -1 && conFlag != 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/7/5 8:54
     * @describe 安卓端改变所有阀门状态
    */
    @RequestMapping("changeAllValve_android")
    @ResponseBody
    public String changeAllValve(HttpServletRequest request) throws JSONException {
        //接收客户端数据
        String valveState = request.getParameter("valveState");
        //发送给终端的数据
        String stateData = "{'flags':'2','data':{'valveNum':'5','state':'"+valveState+"'}}";  //阀门状态
        //将数据转换为json对象
        JSONObject jsonStateData = new JSONObject(stateData);
        //发送指令
        int stateId = InstructAndResult.sendInstructs(123456 ,jsonStateData);
        //返回结果
        JSONObject resultStateJson = InstructAndResult.getResult(stateId);
        Integer stateFlag = resultStateJson.getInt("flag");
        if (stateFlag != -1 && stateFlag != 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    /**
     * @author ZhouGuoWei
     * @date 2018/7/6 20:57
     * @describe 给安卓视屏接口
     */

    @RequestMapping("Video")
    public String Video(){
        return "one";
    }

}
